import 'package:flutter/material.dart';
import 'package:flutter_trip/pages/home_page.dart';
import 'package:flutter_trip/pages/my_page.dart';
import 'package:flutter_trip/pages/search_page.dart';
import 'package:flutter_trip/pages/travel_page.dart';

class TabNavigator extends StatefulWidget {
  @override
  _TabNavigatorState createState() => _TabNavigatorState();
}

class _TabNavigatorState extends State<TabNavigator> {
  // 定义一个页面控制器
  final PageController _controller = PageController(
    initialPage: 0,
    keepPage: true,
  );
  // 定义默认颜色常量
  final _defaultColor = Colors.grey;
  // 选中颜色
  final _activeColor = Colors.blue;
  // 当前选中的索引
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        physics: NeverScrollableScrollPhysics(), // 设置页面不滚动
        controller: _controller,
        children: [
          HomePage(),
          SearchPage(hideLeft: true),
          TravelPage(),
          MyPage()
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: [
          _bottomNavItem(Icons.home, _defaultColor, _activeColor, '首页', 0),
          _bottomNavItem(Icons.search, _defaultColor, _activeColor, '搜索', 1),
          _bottomNavItem(Icons.camera, _defaultColor, _activeColor, '旅拍', 2),
          _bottomNavItem(Icons.person, _defaultColor, _activeColor, '我的', 3),
        ],
        currentIndex: _currentIndex,
        onTap: (index) {
          // 跳转到相应页面
          _controller.jumpToPage(index);
          // 改变索引
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }

  _bottomNavItem(IconData iconName, Color defaultColor, Color activeColor,
      String text, int index) {
    return BottomNavigationBarItem(
      icon: Icon(iconName, color: defaultColor),
      activeIcon: Icon(iconName, color: activeColor),
      title: Text(
        text,
        style: TextStyle(
          color: _currentIndex != index ? _defaultColor : _activeColor,
        ),
      ),
    );
  }
}
